package com.lanou.renrenxin.singleton;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.base.BaseApplication;
import com.lanou.renrenxin.dao.ChatList;
import com.lanou.renrenxin.dao.ChatListDao;
import com.lanou.renrenxin.dao.DaoMaster;
import com.lanou.renrenxin.dao.DaoSession;
import com.lanou.renrenxin.mybomb.MyUser;
import com.lanou.renrenxin.tools.LogUtils;
import com.lanou.renrenxin.tools.RenrenCache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by zouhui on 16/3/4.
 */
public class RenrenxinSingleton {
    private DaoMaster daoMaster;
    private SQLiteDatabase sqLiteDatabase;
    private DaoSession daoSession;
    private RenrenCache renrenCache;
    private ImageLoader imageLoader;
    private RequestQueue requestQueue;
    private MyUser myUser;
    private BmobQuery<MyUser> query;


    private static class SingleHolder {
        private static RenrenxinSingleton instence = new RenrenxinSingleton();
    }

    public static RenrenxinSingleton getInstence() {
        return SingleHolder.instence;
    }

    public RenrenxinSingleton() {
        daoMaster = getDaoMaster();
        sqLiteDatabase = getSqLiteDatabase();
        daoSession = getDaoSession();
        renrenCache = getRenrenCache();
        imageLoader = getImageLoader();
        requestQueue = getRequestQueue();
        myUser = getMyUser();
    }


    public BmobQuery<MyUser> getQuery() {
        if (query == null){
            query = new BmobQuery<>();
        }
        return query;
    }

    public MyUser getMyUser() {
        if (null == myUser) {
            myUser = new MyUser();
        }
        return myUser;
    }

    public ImageLoader getImageLoader() {
        if (null == imageLoader) {
            return imageLoader = new ImageLoader(getRequestQueue(), getRenrenCache());
        }
        return imageLoader;
    }

    public RenrenCache getRenrenCache() {
        if (null == renrenCache) {
            renrenCache = new RenrenCache();
        }
        return renrenCache;
    }

    public RequestQueue getRequestQueue() {
        if (null == requestQueue) {
            return requestQueue = Volley.newRequestQueue(BaseApplication.getContext());
        }
        return requestQueue;
    }

    public DaoMaster getDaoMaster() {
        if (null == daoMaster) {
            return daoMaster = new DaoMaster(getSqLiteDatabase());
        }
        return daoMaster;
    }

    public DaoSession getDaoSession() {
        if (null == daoSession) {
            return daoSession = getDaoMaster().newSession();
        }
        return daoSession;
    }

    public SQLiteDatabase getSqLiteDatabase() {
        if (null == sqLiteDatabase) {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(BaseApplication.getContext(), "Renrenxin.db", null);
            sqLiteDatabase = helper.getWritableDatabase();
            return sqLiteDatabase;
        }
        return sqLiteDatabase;
    }

    /**
     * 查询聊天列表
     *
     * @param mUsername 用户名
     * @return
     */
    public List<ChatList> queryChatList(String mUsername) {
        List<ChatList> chatLists = new ArrayList<>();
        QueryBuilder builder = getInstence().getDaoSession().getChatListDao().queryBuilder();
        builder.where(ChatListDao.Properties.MUsername.eq(mUsername));
        chatLists = builder.list();
        return chatLists;
    }

    /**
     * 存储最新聊天记录
     *
     * @param chat 聊天实体类
     */
    public void saveChatList(ChatList chat) {
        getInstence().getDaoSession().getChatListDao().insertOrReplace(
                new ChatList(chat.getMUsername(), chat.getUsername(),
                        chat.getBody(), chat.getType(), chat.getTime(), chat.getStatus(), chat.getMsg_type()));
    }

    /**
     * 添加图片请求
     *
     * @param imageRequest
     */
    public void addImageRequest(ImageRequest imageRequest) {
        getInstence().getRequestQueue().add(imageRequest);
    }

    /**
     * 加载网络图片
     *
     * @param networkImageView 显示图片的控件
     * @param url              图片地址
     */
    public void loadNetWorkImage(NetworkImageView networkImageView, String url) {
        LogUtils.e("RenrenxinSingleton", url);
        networkImageView.setErrorImageResId(R.mipmap.erro_img);
        networkImageView.setDefaultImageResId(R.mipmap.defult_img);
        networkImageView.setImageUrl(url, getImageLoader());
    }

    public void saveUserData(String username, String nick, String password, BmobFile file, String address,
                             String charactertxt, String sex, String regional) {
        getInstence().getMyUser().setUsername(username);
        getInstence().getMyUser().setPassword(password);
        getInstence().getMyUser().setNick(nick);
        getInstence().getMyUser().setPic(file);
        getInstence().getMyUser().setAddress(address);
        getInstence().getMyUser().setCharactertxt(charactertxt);
        getInstence().getMyUser().setRegional(regional);
        getInstence().getMyUser().setSex(sex);

        getInstence().getMyUser().save(BaseApplication.getContext(), new SaveListener() {
            @Override
            public void onSuccess() {
                LogUtils.e("USER", "保存成功");
            }

            @Override
            public void onFailure(int i, String s) {
                LogUtils.e("USER", "保存失败");
            }
        });
    }

    public void queryMatchsUsername(String username, final Handler handler) {

        query = getQuery();
        query.addWhereMatches("username", username);
        query.findObjects(BaseApplication.getContext(), new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                Message message = new Message();
                message.what = 756;
                message.obj = list;
                handler.sendMessage(message);
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }


    public void queryAllUsername(final Handler handler) {


        query = getQuery();
        query.findObjects(BaseApplication.getContext(), new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                Message message = new Message();
                message.what = 757;
                message.obj = list;
                handler.sendMessage(message);
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }



    public void loadHeadImage(final String username) {
        LogUtils.e("¶¶¶¶¶", "加载头像");
        query = getQuery();
        query.addWhereEqualTo("username", username);
        query.findObjects(BaseApplication.getContext(), new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                for (MyUser user : list) {
                    if (user.getPic() != null) {
                        saveImageUrl(username, user.getPic().getFileUrl(BaseApplication.getContext()));
                        volleyLoadImgae(user.getPic().getFileUrl(BaseApplication.getContext()));
                    }
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });


    }

    public void volleyLoadImgae(final String url) {
        LogUtils.e("¶¶¶¶¶", "加载头像");
        ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                Log.e("∂∂∂∂∂∂∂∂∂", response.toString());
                saveImage(response, url);

            }
        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("ERROR", error.getMessage());
            }
        });
        addImageRequest(request);

    }


    public void saveImage(Bitmap bitmap, String path) {
        String cacheDir = null;
        Log.e("ßßßß", bitmap.toString());
        if (bitmap != null) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//SD卡是否挂载
                File root = Environment.getExternalStorageDirectory();
                File ruiCache = new File(root.getAbsolutePath() + "/Renrenxin");
                if (!ruiCache.exists()) {
                    ruiCache.mkdir();
                }
                cacheDir = ruiCache.getAbsolutePath();
            }
        }
        if (path.contains(".jpg") || path.contains(".png")) {
            path = path.substring(path.lastIndexOf("/"), path.lastIndexOf(".") + 4);
            FileOutputStream fos = null;
            try {
                //初始化文件写入对象   添加路径
                fos = new FileOutputStream(cacheDir + "/" + path);
                //保存bitmap
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (null != fos) {
                    try {
                        //这么写 怎么都会关
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public Bitmap getDiskBitmap(String path) {
        String cacheDir = null;
        Bitmap bitmap = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//SD卡是否挂载
            File root = Environment.getExternalStorageDirectory();
            File ruiCache = new File(root.getAbsolutePath() + "/Renrenxin");
            if (!ruiCache.exists()) {
                ruiCache.mkdir();
            }
            cacheDir = ruiCache.getAbsolutePath();
        }
        if (path.contains(".jpg")||path.contains(".png")) {
            path = path.substring(path.lastIndexOf("/"), path.lastIndexOf(".") + 4);
            bitmap = BitmapFactory.decodeFile(cacheDir + path);
            LogUtils.e("RenrenxinSingleton", bitmap.toString());
            return bitmap;
        }else{
            LogUtils.e("RenrenxinSingleton", path);
            return null;
        }
    }

    public void saveImageUrl(String username, String url) {
        SharedPreferences sharedPreferences =
                BaseApplication.getContext().getSharedPreferences("HEADIMAGE_URL", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(username, url);
        editor.commit();
    }

    public String getImageUrl(String username) {
        String url = new String();
        SharedPreferences sharedPreferences =
                BaseApplication.getContext().getSharedPreferences("HEADIMAGE_URL", Context.MODE_PRIVATE);
        url = sharedPreferences.getString(username, "");
        return url;
    }


}
